<template>
  <el-dialog :title="t('keys.edit_pwd')" v-model="dialogVisible" width="400px" :close-on-click-modal="false">
    <zcb-radio-c v-model="pwdForm.verifyType" :list="lovValueList" :width="100" style="margin-bottom:20px" @change="onRadioChange"></zcb-radio-c>
    <el-form ref="pwdFormRef" :model="pwdForm" :rules="rules" label-width="0" label-position="left">
      <el-form-item prop="password" v-if="pwdForm.verifyType === 0">
        <el-input
          v-model="pwdForm.password"
          maxlength="16"
          style="width: 100%"
          clearable
          :placeholder="t('keys.Please_enter_the_current_password')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="phone" v-if="pwdForm.verifyType === 1">
        <el-input
          v-model="pwdForm.phone"
          :disabled="props.detailInfo.phone ? true : false"
          maxlength="16"
          style="width: 100%"
          clearable
          :placeholder="t('keys.phonePlaceholder')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="email" v-if="pwdForm.verifyType === 2">
        <el-input
          v-model="pwdForm.email"
          :disabled="props.detailInfo.email ? true : false"
          maxlength="16"
          style="width: 100%"
          clearable
          :placeholder="t('keys.emailPlaceholder')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="captcha" v-if="pwdForm.verifyType === 1 || pwdForm.verifyType === 2">
        <el-input
          v-model.trim="pwdForm.captcha"
          type="text"
          maxlength="6"
          :placeholder="t('keys.Verification_Code')"
          oninput="if(value.length>8)value=value.slice(0,8)"
          style="width: 63%"
          clearable
        >
        </el-input>
        <el-button style="width: 36%" :disabled="smsObj.count != 0" plain @click.stop="sendSms">{{ smsObj.content }}</el-button>
      </el-form-item>
      <el-form-item prop="newPassword">
        <el-popover ref="popover" placement="top" :width="300" trigger="click">
          <template #default>
            <zcb-tit :title="t('keys.Password_rules')"></zcb-tit>
            <div class="pass-vali">
              <span v-for="item in passVali" :class="item.status ? 'ok' : ''">
                <el-icon><CircleCheck /></el-icon>
                {{ item.label }}
              </span>
            </div>
            <zcb-tit :title="t('keys.Password_strength')"></zcb-tit>
            <el-progress :percentage="percentage" :show-text="false" :color="customColor" />
          </template>
          <template #reference>
            <el-input
              v-model.trim="pwdForm.newPassword"
              type="password"
              show-password
              autocomplete="new-password"
              :placeholder="t('keys.passwordPlaceholder')"
              maxLength="16"
              clearable
            >
            </el-input>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="pwdForm.confirmPassword"
          minlength="8"
          type="password"
          show-password
          maxlength="16"
          style="width: 100%"
          clearable
          :placeholder="t('keys.Please_enter_the_new_password_again')"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ t('keys.cancel') }}</el-button>
        <el-button type="primary" @click="pwdSubmit(pwdFormRef)">{{ t('keys.ok') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { validPasswordNew } from 'utils/validate'
import { postUpdatePasswordApi, getEmailValidateUpdataApi, getPhoneValidateApi } from 'api/home'
import { ERR_OK } from 'config/statusCode'
import { validatePhone, validateEmail } from 'utils/validate.js'
const { t } = useI18n() // 中英文

const emit = defineEmits(['refresh'])
const props = defineProps({
  detailInfo: {
    type: Object,
    default: () => {}
  }
})
const lovValueList = ref([])
const pwdFormRef = ref(null)
const pwdForm = ref({
  phone: '',
  email: '',
  captcha: '',
  verifyType: 0,
  password: '',
  newPassword: '',
  confirmPassword: ''
})
let passVali = ref([
  {
    value: 30,
    label: t('keys.The_total_length_of_the_password_is_8_16_characters'),
    status: false
  },
  {
    value: 31,
    label: t('keys.Must_include_English_uppercase_and_lowercase_letters'),
    status: false
  },
  {
    value: 32,
    label: t('keys.Must_include_numbers'),
    status: false
  },
  {
    value: 33,
    label: t('keys.Can_be_used') + '【@$!%*?&】' + t('keys.Symbols_increase_password_strength'),
    status: false
  }
])
const percentage = ref(0)
const customColor = ref('#f56c6c')

const smsObj = reactive({
  content: t('keys.Get_verification_code'),
  count: 0,
  timerSms: null
})
const checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t('keys.phone_cant_empty')))
  }
  setTimeout(() => {
    if (!Number.isInteger(+value)) {
      callback(new Error(t('keys.please_enter_number_tips')))
    } else {
      if (validatePhone(value)) {
        callback()
      } else {
        callback(new Error(t('keys.reg_tele_empty_format_tips')))
      }
    }
  }, 100)
}
var checkEmail = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t('keys.email_empty')))
  } else {
    if (validateEmail(value)) {
      callback()
    } else {
      callback(new Error(t('keys.email_vis_empty')))
    }
  }
}
const validateNewPassword = (rule, value, callback) => {
  if (!value) {
    passVali.value[0].status = false
    passVali.value[1].status = false
    passVali.value[2].status = false
    passVali.value[3].status = false
    percentage.value = 0
    callback(new Error(t('keys.Password_format_tips')))
  } else {
    let arr = [0, 0, 0, 0]
    if (value.length >= 8 && value.length <= 16) {
      passVali.value[0].status = true
      arr[0] = 25
    } else {
      passVali.value[0].status = false
      arr[0] = 0
    }
    let regEn = /(?=.*[a-z])(?=.*[A-Z])/
    if (regEn.test(value)) {
      passVali.value[1].status = true
      arr[1] = 25
    } else {
      passVali.value[1].status = false
      arr[1] = 0
    }
    let regNum = /(?=.*[a-zA-Z])(?=.*\d)/
    if (regNum.test(value)) {
      passVali.value[2].status = true
      arr[2] = 25
    } else {
      passVali.value[2].status = false
      arr[2] = 0
    }
    let regSym2 = /[^a-zA-Z0-9]/
    // 校验是否包含特殊符号
    if (regSym2.test(value)) {
      // 如果包含特殊符号  必须是@$!%*?&其中一个
      let regSym = /[@$!%*?&]+$/
      if (regSym.test(value)) {
        passVali.value[3].status = true
        arr[3] = 25
      } else {
        passVali.value[3].status = false
        arr[3] = 0
      }
    }
    percentage.value = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
    customColor.value =
      percentage.value === 25
        ? '#f56c6c'
        : percentage.value === 50
        ? '#FF6700'
        : percentage.value === 75
        ? '#e6a23c'
        : percentage.value === 100
        ? '#67c23a'
        : '#f56c6c'
    if (!validPasswordNew(value)) {
      callback(new Error(t('keys.The_password_format_is_incorrect')))
    } else {
      callback()
    }
  }
  // if (!value) {
  //   callback(new Error(t('keys.Please_enter_a_new_password')))
  // } else if (validPasswordNew(value)) {
  //   callback()
  // } else {
  //   callback(new Error(t('keys.Password_length_verification_again')))
  // }
}
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error(t('keys.Please_enter_the_confirmation_password')))
  } else if (value !== pwdForm.value.newPassword) {
    callback(new Error(t('keys.The_two_passwords_are_inconsistent')))
  } else {
    callback()
  }
}
const rules = reactive({
  phone: [{ required: true, validator: checkPhone, trigger: ['blur', 'change'] }],
  email: [{ validator: checkEmail, trigger: ['blur', 'change'] }],
  captcha: [{ required: true, message: t('keys.captchaCodePlaceholder'), trigger: ['blur', 'change'] }],
  password: [{ required: true, message: t('keys.Please_enter_the_original_password'), trigger: 'blur' }],
  newPassword: [{ required: true, validator: validateNewPassword, trigger: ['blur', 'change'] }],
  confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: ['blur', 'change'] }]
})
const dialogVisible = ref(false)
const onRadioChange = () => {
  pwdFormRef.value?.resetFields()
}
// 发送验证码
const sendSms = () => {
  if (smsObj.count > 0) {
    return
  }
  if (!(pwdForm.value.verifyType == 1)) {
    // 校验手机号
    if (pwdForm.value.verifyType == 1) {
      if (!pwdForm.value.telephone) {
        ElMessage.error(t('keys.phonePlaceholder'))
        return
      }
      if (!validatePhone(pwdForm.value.telephone)) {
        ElMessage.error(t('keys.Please_enter_the_correct_mobile_number'))
        return
      }
    } else {
      if (!pwdForm.value.email) {
        ElMessage.error(t('keys.emailPlaceholder'))
        return
      }
      if (!validateEmail(pwdForm.value.email)) {
        ElMessage.error(t('keys.emailokPlaceholder'))
        return
      }
    }
  }
  let param = {
    number: pwdForm.value.verifyType == 1 ? pwdForm.value.telephone : pwdForm.value.email,
    type: pwdForm.value.verifyType == 1 ? 'SMS' : 'EMAIL'
  }
  let aprUrl = pwdForm.value.verifyType == 1 ? getPhoneValidateApi : getEmailValidateUpdataApi
  // 请求后台发送验证码至手机
  aprUrl(pwdForm.value.verifyType == 1 ? '' : param).then((res) => {
    if (res.code === ERR_OK) {
      ElMessage.success(t('keys.Verification_code_has_been_sent'))
      // 控制倒计时及按钮是否可以点击
      const TIME_COUNT = 60
      smsObj.count = TIME_COUNT
      smsObj.timerSms = window.setInterval(() => {
        if (smsObj.count > 0 && smsObj.count <= TIME_COUNT) {
          // 计时秒数
          smsObj.count--
          // 更新按钮的文字内容
          smsObj.content = smsObj.count + 's' + t('keys.Reacquire_after')
        } else {
          smsObj.content = t('keys.Get_verification_code')
          // 清空定时器!!!
          clearInterval(smsObj.timerSms)
          smsObj.timerSms = null
        }
      }, 1000)
    }
  })
}
const showDialog = (data) => {
  // userType:  // DOMESTIC - 中国用户 || OVERSEAS - 国际用户
  let json = [{ code: 0, name: '使用旧密码' }]
  if (props.detailInfo.userType === 'DOMESTIC') {
    lovValueList.value = json.concat({ code: 1, name: '使用手机验证' })
    pwdForm.value.phone = props.detailInfo.phone
  } else if (props.detailInfo.userType === 'OVERSEAS') {
    lovValueList.value = json.concat({ code: 2, name: '使用邮箱验证' })
    pwdForm.value.email = props.detailInfo.email
  }
  dialogVisible.value = true
  pwdFormRef.value?.resetFields()
}
// 提交修改密码
const pwdSubmit = async (pwdFormRef) => {
  if (!pwdFormRef) return
  await pwdFormRef.validate(async (valid, fields) => {
    if (valid) {
      const params = { ...pwdForm.value }
      const { code, desc } = await postUpdatePasswordApi(params)
      if (code === ERR_OK) {
        ElMessage({
          message: t('keys.modified'),
          type: 'success'
        })
        emit('refresh')
        dialogVisible.value = false
      }
    }
  })
}
defineExpose({
  showDialog
})
</script>
<style lang="scss" scoped>
.pass-vali {
  display: flex;
  flex-direction: column;
  color: #666;
  span {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    .el-icon {
      margin-right: 10px;
    }
    &.ok {
      color: var(--el-color-success);
    }
  }
}
</style>
